package com.woniu.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.entity.Dept;
import com.woniu.entity.Project;
import com.woniu.entity.User;
import com.woniu.entity.response.ResponseEntity;
import com.woniu.entity.vo.PageProject;
import com.woniu.entity.vo.ProjectExcel;
import com.woniu.entity.vo.UserExcel;
import com.woniu.exception.controllerException.ProjectCouldNotUseException;
import com.woniu.exception.controllerException.ProjectExistException;
import com.woniu.service.IProApproveService;
import com.woniu.service.IProjectService;
import com.woniu.service.IUserService;
import com.woniu.util.ExcelResponseHeaderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/brain/project")
public class ProjectController {
    @Autowired
    private IProjectService projectService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IProApproveService proApproveService;

    @Value("${project.contract}")
    private String contract;

    @RequestMapping("/add")
    public ResponseEntity addProject(@RequestBody Project project) {
        if (projectService.getByProId(project.getProId())!=null) {
            throw new ProjectExistException("项目已存在");
        }
            project.setProStatus("s");
            projectService.add(project);
            return ResponseEntity.success(project);
    }

    @RequestMapping("/update/{proId}")
    public ResponseEntity updateProject(@RequestBody  Project project,@PathVariable int proId) {
        if(project.getProStatus().equals("e")){
            throw new ProjectCouldNotUseException("项目已结题");
        } else if (project.getProStatus().equals("r")) {
            throw new ProjectCouldNotUseException("项目已在审批中，请待审批结束");
        }
        //修改不能这样
        //要判断剩余金额小于所要花销金额,
        projectService.update(project);
        return ResponseEntity.success(project);
    }

    @RequestMapping("/end/{proId}")//结题
    public ResponseEntity endProject(@RequestBody  Project project,@PathVariable int proId) {
        project=projectService.getByProId(proId);
        //判断时间
//        int currentTime=Integer.parseInt(DateUtils.getDate(LocalDateTime.now().toString().replace("-","")));
//        int proEndTime=Integer.parseInt(DateUtils.getDate(project.getProEndTime().toString()));
//        if(currentTime>=proEndTime) {
        if(Integer.parseInt(project.getEndTime())>=Integer.parseInt(project.getProEndTime())) {
            project.setProStatus("e");
            projectService.update(project);
        }
        return ResponseEntity.success(project);
    }

    @RequestMapping("/get/{proId}")
    public ResponseEntity getProjectByProId(@PathVariable("proId") Integer proId) {
        return ResponseEntity.success(projectService.getByProId(proId));
    }

    @RequestMapping("/list")
    public ResponseEntity getProjectByCondition(@RequestBody(required = false) Project project) {
        return ResponseEntity.success(projectService.getByCondition(project));
    }

    @RequestMapping("/pageList")
    public ResponseEntity getProjectByConditionWithPage(@RequestBody PageProject pageProject) {
        if (pageProject.getP() == null || pageProject.getP() == 0) {
            pageProject.setP(1);
        }
        return ResponseEntity.success(projectService.getByPage( pageProject.getProject(),pageProject.getP()));
    }


    @RequestMapping("/upload/{proId}")
    public ResponseEntity uploadProContract(MultipartFile file, @PathVariable Integer proId) {
        //先判断文件是否上传
        //先找原始的名字
        String originName = file.getOriginalFilename();
        String type = file.getContentType();
        //判断文件类型是不是pdf
        if(!originName.endsWith(".pdf")){
            //如果不是的话，就返回类型
            return ResponseEntity.fail(type,"文件格式不正确");
        }
        //文件名要用UUID重新产生
        String name =UUID.randomUUID() + originName.substring(originName.lastIndexOf("."));
        String path=contract+"\\"+name;
        //文件夹提供配置文件指定
        try {
            // file.transferTo(new File("D://90dest//"+file.getOriginalFilename()));
            file.transferTo(new File(path));
            Project project=projectService.getByProId(proId);
            project.setContract(path);
            projectService.update(project);
            return ResponseEntity.success(name);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.fail(null);
        }
    }

    @RequestMapping("/download")
    public void downloadExcel(@RequestBody(required = false) Project project, HttpServletResponse response) throws IOException {
        List<Project> projectList = projectService.getByCondition(project);
        List<ProjectExcel> projectExcels = new CopyOnWriteArrayList<>();
        for (Project project1 : projectList) {
            ProjectExcel projectExcel = new ProjectExcel();
            projectExcel.setProId(String.valueOf(project1.getProId()));
            projectExcel.setProName(project1.getProName());
            projectExcel.setBank(String.valueOf(project1.getBank().getBankId()));
            projectExcel.setUser(project1.getUser().getUserName());
            projectExcel.setContract(project1.getContract());
            projectExcel.setProStartTime(project1.getProStartTime());
            projectExcel.setProEndTime(project1.getProEndTime());
            projectExcel.setPrePrice(project1.getPrePrice());
            projectExcel.setProStatus(project1.getProStatus());
            projectExcels.add(projectExcel);
        }
        ExcelResponseHeaderUtil.setExcelRespProp(response, "项目表");
        EasyExcel.write(response.getOutputStream())
                .head(ProjectExcel.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("项目表")
                .doWrite(projectExcels);
    }


}
